package gdingtalk

import (
	"fmt"
)

var (
	gDingTalk IDingTalk
)

// GetDingTalk 获取dingTalk
func GetDingTalk() IDingTalk {
	return gDingTalk
}

type IDingTalk interface {
	GetAccessToken(corpId string) (string, error)
	GetAgentId(corpId string) (int64, error)
}

// GetAuth 授权相关操作
func GetAuth() *Auth {
	auth := NewAuth()
	return &auth
}

// GetDepartment 部门相关操作
func GetDepartment() *Department {
	dept := NewDepartment()
	return &dept
}

// GetUser 授权相关操作
func GetUser() *User {
	// 默认只同步企业下1000人数据，如果需要自己调整该值，请用NewUser自己实例化
	user := NewUser(1000)
	return &user
}

// Init 初始化各种组件
func Init(option Option) error {
	gOption = option
	err := initCache(gOption.CacheConn)
	if err != nil {
		return err
	}

	if gOption.DbConn != "" {
		err1 := initDb(gOption.DbConn)
		if err1 != nil {
			return err1
		}
	}

	err = initDingTalk()
	if err != nil {
		return err
	}
	return nil
}

// initDingTalk
func initDingTalk() error {
	var err error
	switch gOption.Type {
	case "isv":
		var isv Isv
		isv, err = NewIsv(gOption.DingParams)
		gDingTalk = &isv
	case "corp":
		var corp Corp
		corp, err = NewCorp(gOption.DingParams)
		gDingTalk = &corp
	default:
		err = fmt.Errorf("type %s is not support", gOption.Type)
	}
	return err
}
